import { createAction } from 'redux-actions';
import * as types from '../constants/ActionTypes';
import * as authService from '../services/authService';
import * as storage from '../services/storage';

export const tryAuth = createAction(types.CHECK_TOKEN, async (token) => {
  const result = await authService.tryAuth();

  if (result) {
    storage.setUser(result.user);
  } else {
    storage.removeUser();
  }

  return result;
});

export const onSignin = createAction(types.SIGNIN, async (name, password) => {
  const result = await authService.signin(name, password);

  if (result) {
    storage.setUser(result.user);
  } else {
    storage.removeUser();
  }

  return result;
});

export const onRegister = createAction(types.SIGNUP, async (name, email, password, rePassword, code) => {
  const result = await authService.signup(name, email, password, rePassword);

  if (result) {
    storage.setUser(result.user);
  } else {
    storage.removeUser();
  }

  return result;
});

export const onSignout = createAction(types.SIGNOUT, async () => {
  storage.removeUser();
  const result = await authService.signout();
  return result;
});
